import {
	inWhiteList
} from './whiteList'
import {
	getToken
} from './auth'
import message from "./message"
import obj from "@/config/index"
import {
	validateParmasHasEmoji,
	replaceAllTimeStringToTimeStamp
} from "./validateEmoji"
import {
	log
} from 'util'
const baseUrl = obj.BASE_URL
// const baseUrl = 'http://139.9.41.8/cdsa-web/'
// const baseUrl = 'http://192.168.1.132:5026/cdsa-web/' //佳哥的
// const baseUrl = 'http://192.168.20.24:5027/cdsa-web/' 
// 判断数据类型是否为formdata
function isFormData(v) {
	return Object.prototype.toString.call(v) === '[object FormData]'
}

uni.addInterceptor('request', {
	invoke(config) {
		let isOwnerProjectId = uni.getStorageSync("isOwner")
		let isShowPopup = uni.getStorageSync("isShowPopup")
		if (isOwnerProjectId && config.data && isShowPopup) {
			if (isFormData(config.data) && !config.data.has('projectId')) {
				// 当为formdata类型
				config.data.set('projectId', isOwnerProjectId)
			} else if (config.data.projectId === null) {
				delete config.data.projectId
			} else if (!config.data.projectId) {
				// 当为普通的对象时
				if (config.data.currPage && config.data.pageSize) {
					config.data.params.projectId = isOwnerProjectId
				}
				config.data.projectId = isOwnerProjectId
			}
		}
	},
	success(args) {
		let res = args.data
		if (res.status === 0) {
			// console.log(res.message);
			message(res.message)
		}
		if (res.status === 1001) {
			message("登录超时，请重新登录", {
				duration: 1000
			})
			setTimeout(() => {
				uni.reLaunch({
					url: "/pages/login/login"
				})
			}, 1500)
		}
		return res
	},
	fail(err) {
		message(err.message)
		return err
	},
})
// #ifdef APP-PLUS || MP-WEIXIN
uni.addInterceptor('chooseImage', {
	success(args = {}) {
		let invalidSuffix = ['.heic']
		let bool = false
		args.tempFilePaths = (args.tempFilePaths || []).filter(item => {
			let tempObj = invalidSuffix.find(item1 => item.endsWith(item1))
			if (tempObj) {
				bool = true
				return false
			}
			return true
		})
		args.tempFiles = (args.tempFiles || []).filter(item => {
			let tempObj = invalidSuffix.find(item1 => item.path.endsWith(item1))
			if (tempObj) {
				bool = true
				return false
			}
			return true
		})
		if (bool) {
			message("已自动过滤未识别文件", {
				duration: 3000
			})
		}
	},
})
// #endif
uni.addInterceptor('uploadFile', {
	success(args) {
		let res = JSON.parse(args.data)
		if (res.status === 0) {
			message(res.message)
		}
		if (res.status === 1001) {
			message("登录超时，请重新登录")
			setTimeout(() => {
				uni.reLaunch({
					url: "/pages/login/login"
				})
			}, 1500)
		}
		return args
	},
	fail(err) {
		message(err.message)
		return err
	},
})
export default ({
	url,
	data
}) => {
	const header = {
		'content-type': 'application/json;charset=UTF-8',
		'accept': 'application/json;charset=UTF-8',
	}
	header['x-auth-token'] = inWhiteList(url) ? '' : getToken()
	if (validateParmasHasEmoji(data)) {
		message('请勿输入特殊符号！')
		return new Promise(() => {})
	}
	replaceAllTimeStringToTimeStamp(data)
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url, //仅为示例，并非真实接口地址。
			data,
			method: "POST",
			header,
			success: (res) => {
				resolve(res.data)
			},
			fail: (error) => {
				console.error('[uni.request][error]', error)
				reject(error)
			}
		});
	})
}

export const uploadFile = ({
	url,
	formData = {},
	filePath,
	name = "attach",
	files = [],
	isOffline = false,
	timeout = 6 * 1000 * 10,
	taskBack = (() => {})
}) => {
	const header = {}
	header['x-auth-token'] = inWhiteList(url) ? '' : getToken()
	// header['x-auth-token'] = "9de55dbc-a6ed-4efa-97db-5c9bcb5bc583"
	return new Promise((resole, reject) => {
		const task = uni.uploadFile({
			url: baseUrl + url,
			files,
			filePath,
			name,
			header,
			timeout,
			formData,
			success: (res) => {
				console.log("resresresres1111", JSON.parse(res.data))
				if (!isOffline) {
					resole(res.data)
				} else {
					resole({
						success: true,
						result: {
							id: JSON.parse(res.data).result.id
						}
					})
				}
			},
			fail: err => reject(err)
		});
		task.onProgressUpdate(taskBack)
	})
}

export const uploadVideoFile = ({
	url,
	formData = {},
	files = [],
	isOffline = false
}) => {
	const header = {}
	header['x-auth-token'] = inWhiteList(url) ? '' : getToken()
	// header['x-auth-token'] = "9de55dbc-a6ed-4efa-97db-5c9bcb5bc583"
	return new Promise((resole, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			files,
			filePath: '',
			name: '',
			header,
			formData,
			success: (res) => {
				// console.log("resresresres", res)
				if (!isOffline) {
					resole(res.data)
				} else {
					resole({
						success: true,
						result: {
							id: JSON.parse(res.data).result.id
						}
					})
				}
			},
			fail: err => console.error(err)
		});
	})
}

export const uploadRecord = (url, fileUrl) => {
	const header = {}
	header['x-auth-token'] = inWhiteList(url) ? '' : getToken()
	return new Promise((resole, reject) => {
		uni.uploadFile({
			url: obj.RECORD_BASE_URL + url,
			filePath: fileUrl,
			name: 'file',
			header,
			success: (res) => {
				console.log("resresresres", res)
				resole(res.data)
			},
			fail: err => console.error(err)
		});
	})
}

//其实要实现的效果就是app禁止输入特殊字符和表情 当判断到属性值为表情时弹出提示（'存在未能解析的文本'）
//我的意思是想在request封装里面做处理。 一般入参的形式不就是对象，然后对象里面可能存在数组，数组里面又有对象，我要判断每个key值